package io.lvdaxian.jdbc.demo;

import com.alibaba.fastjson2.JSON;
import com.mysql.cj.jdbc.Driver;
import io.lvdaxian.jdbc.entity.User;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class JDBCDemo {
  
  private final static String url = "jdbc:mysql://127.0.0.1:3306/mybatis?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai";
  private final static String user = "root";
  private final static String password = "root";
  
  
  static {
    try {
      // 驱动管理者 进行 驱动注册
      DriverManager.registerDriver(new Driver());
    } catch (SQLException e) {
      throw new RuntimeException(e);
    }
  }
  
  /**
   * 获取 connect 连接
   *
   * @return 返回 Connection 连接
   * @author lihh
   */
  private static Connection getConnection() {
    try {
      return DriverManager.getConnection(url, user, password);
    } catch (SQLException e) {
      throw new RuntimeException(e);
    }
  }
  
  public static String querySelectString(String id) throws SQLException {
    Connection connection = getConnection();
    
    Statement statement = connection.createStatement();
    ResultSet resultSet = statement.executeQuery(String.format("select * from user where id = '%s'", id));
    
    return JSON.toJSONString(processorUserHandler(resultSet));
  }
  
  private static List<User> processorUserHandler(ResultSet resultSet) throws SQLException {
    List<User> list = new ArrayList<>();
    
    for (; resultSet.next(); ) {
      int id = resultSet.getInt("id");
      String userId = resultSet.getString("userId");
      String userHead = resultSet.getString("userHead");
      String userName = resultSet.getString("userName");
      
      list.add(User.builder().id(id).userName(userName).userHead(userHead).userId(userId).build());
    }
    
    return list;
  }
  
  public static String querySelectStr(String id) throws SQLException {
    Connection connection = getConnection();
    
    PreparedStatement preparedStatement = connection.prepareStatement("select * from user where id = ?");
    preparedStatement.setString(1, id);
    
    ResultSet resultSet = preparedStatement.executeQuery();
    return JSON.toJSONString(processorUserHandler(resultSet));
  }
}
